package com.apop.accompanyH5.order.controller;

import cn.hutool.core.bean.BeanUtil;
import com.apop.accompanyH5.ServletUtils;
import com.apop.accompanyH5.order.constants.OrderConstants;
import com.apop.accompanyH5.order.domain.OrderDO;
import com.apop.accompanyH5.order.domain.vo.OrderReqVO;
import com.apop.accompanyH5.order.domain.vo.OrderRespVO;
import com.apop.accompanyH5.order.enums.OrderStateEnum;
import com.apop.accompanyH5.order.service.OrderService;
import com.apop.common.exception.BizException;
import com.apop.common.model.Result;
import com.apop.common.util.OrderGenerator;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * H5 订单相关接口
 * @ClassName H5OrderController
 * @author Jiayi Zheng
 * @date 2021/11/10 15:35
 * @Description: 测试
 * @version V1.0
 */
@RestController
@Slf4j
@RequestMapping("/pzH5/order")
public class H5OrderController {

    @Value("${server.ip}")
    String ip;
    @Resource
    OrderService orderService;

    /**
     * 提交订单
     *
     * @param reqVO
     * @return
     */
    @PostMapping("/createOrder")
    public Result createOrder(HttpServletRequest request,@Valid @RequestBody OrderReqVO reqVO) {

        log.info("创建订单 {} ", reqVO);

        String account = ServletUtils.getCurrentUserAccount(request);
        log.info("下单账号 {} ", account);

        OrderDO orderDO = BeanUtil.toBean(reqVO, OrderDO.class);
        orderDO.setAccount(account);
        // 生成订单号
        orderDO.setCode(OrderGenerator.generateOrderNumber());
        // 设置订单初始值
        orderDO.setStatus(OrderStateEnum.WAIT_PAYMENT.getState());
        orderService.save(orderDO);
        // 生成支付链接
        String payLink = String.format(OrderConstants.TEST_PAY_LINK,ip,orderDO.getId());
        return Result.success(payLink);
    }

    /**
     * H5-我的订单
     * @param request
     * @param
     * @return
     */
    @GetMapping("/list")
    public Result orderList(HttpServletRequest request, @RequestParam Integer status) {

        log.info("请求参数 {} ", status);
        String account = ServletUtils.getCurrentUserAccount(request);

        // 查询用户订单 根据创建时间倒序
        List list = orderService.list(
                new LambdaQueryWrapper<OrderDO>()
                        .eq(status!=0,OrderDO::getStatus,status)
                        .eq(OrderDO::getAccount,account)
                        .orderByDesc(OrderDO::getCreateTime)
        );

        return Result.success(list);
    }

    /**
     * 订单详情
     * @param orderId
     * @return
     */
    @GetMapping("/detail")
    public Result<OrderRespVO> orderDetail(@RequestParam Integer orderId) {

        log.info("请求参数 orderId={} ", orderId);
        OrderDO orderDO = orderService.getById(orderId);

        OrderRespVO respVO = BeanUtil.toBean(orderDO, OrderRespVO.class);
        // 生成支付链接
        respVO.setPayLink(String.format(OrderConstants.TEST_PAY_LINK,ip,respVO.getId()));
        return Result.success(respVO);
    }

    /**
     * 订单支付回调
     * @param orderId
     * @return
     */
    @GetMapping("/onPaySuccess")
    public Result notifyOrderSuccess(@RequestParam Integer orderId) {
        OrderDO orderDO = orderService.getById(orderId);
        if (orderDO == null){
            throw new BizException("E500","订单信息错误!");
        }
        if (!orderDO.getStatus().equals(OrderStateEnum.WAIT_PAYMENT.getState())){
            throw new BizException("E500","订单状态不正确!");
        }

        onOrderPaySuccess(orderDO);

        // 浏览器重定向
        return Result.success(null);
    }

    /**
     * 订单支付成功
     * @param orderDO
     */
    private void onOrderPaySuccess(OrderDO orderDO){
        orderDO.setStatus(OrderStateEnum.WAIT_SERVICE.getState());
        orderService.updateById(orderDO);
    }

}
